import { SUCCESS_CODE } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import ProForm from '@ant-design/pro-form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Form, Input, message, Modal } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import { useRef, useState } from 'react';
import AddFrom from './components/AddForm';
import type { TenantAddItem, TenantItem, TenantUpdateItem } from './data.d';
import { addTenant, deleteTenant } from '../Tenant/service';
import { queryTenantListByTenant, updateTenant, updateTenantPwd } from './service';
import EditForm from './components/EditForm';
import { useModel } from 'umi';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const {
    'TENANT.ADD': add,
    'TENANT.CHANGE.ROLE': change,
    'TENANT.DELETE': Delete,
    'TENANT.EDIT.BELONG': edit,
    'TENANT.UPDATE': update,
  } = currUser;

  const [sorter, setSorter] = useState<string>('');
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [editInfoVisible, setEditInfoVisible] = useState<boolean>(false);
  const [passwordVisible, setPasswordVisible] = useState<boolean>(false);
  const [tenant, setTenant] = useState<TenantItem | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  async function handleAdd(fields: TenantAddItem) {
    const hide = message.loading('正在添加');

    const res = await addTenant(fields);
    hide();
    if (res.code === SUCCESS_CODE) {
      message.success(res.message || '添加成功');
      actionRef.current?.reload();
    } else {
      message.error(res.message || '添加失败请重试！');
    }
    handleAddModalVisible(false);
  }

  // 删除
  const handleRemove = async (id: string) => {
    const hide = message.loading('正在删除');
    try {
      await deleteTenant(id);
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const editInfoEvent = async (values: TenantUpdateItem) => {
    const res = await updateTenant(values);
    if (res.code === SUCCESS_CODE) {
      message.success(res.message || '修改成功');
      actionRef.current?.reload();
      setEditInfoVisible(false);
    } else {
      message.error(res.message || '修改失败');
    }
  };

  const columns: ProColumns<TenantItem>[] = [
    {
      title: '客户编号',
      dataIndex: 'id',
      ellipsis: true,
    },
    {
      title: '客户名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '账号',
      dataIndex: 'account',
      ellipsis: true,
    },
    {
      title: '密码',
      dataIndex: 'password',
      ellipsis: true,
      search: false,
    },
    {
      title: '角色',
      dataIndex: 'role_name',
      ellipsis: true,
      search: false,
    },
    {
      title: '推送地址',
      dataIndex: 'push_url',
      ellipsis: true,
      search: false,
    },
    {
      title: '联系方式',
      dataIndex: 'mobile',
      ellipsis: true,
      search: false,
    },
    {
      title: '邮箱',
      dataIndex: 'mail',
      ellipsis: true,
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      ellipsis: true,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      search: false,
      ellipsis: true,
      render: (_, record) => {
        const onClickRemove = () => {
          const { id, name } = record;
          Modal.confirm({
            title: `删除客户 ${id}`,
            content: (
              <>
                <Divider />
                <p>确认要删除客户</p>
                <span>{name}</span>?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove(id);
            },
            centered: true,
            width: '30vw',
            style: { height: '18vw' },
          });
        };

        return (
          <div>
            {update && (
              <a
                onClick={() => {
                  setEditInfoVisible(true);
                  setTenant(record);
                }}
              >
                编辑
              </a>
            )}
            <Divider type="vertical" />
            <a
              onClick={() => {
                setPasswordVisible(true);
                setTenant(record);
              }}
            >
              修改密码
            </a>
            {Delete && (
              <>
                <Divider type="vertical" />
                <a onClick={onClickRemove}>删除</a>
              </>
            )}
          </div>
        );
      },
    },
  ];
  return (
    <PageHeaderWrapper title="客户账号管理">
      <ProTable<TenantItem>
        headerTitle={'客户账号管理列表'}
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TenantItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <>
            {add && (
              <Button type="primary" key={''} onClick={() => handleAddModalVisible(true)}>
                <PlusOutlined /> 添加
              </Button>
            )}
          </>,
        ]}
        tableAlertRender={() => false}
        request={(params) => {
          return queryTenantListByTenant(params);
        }}
        columns={columns}
        rowSelection={false}
      />
      {addModalVisible && (
        <AddFrom
          modalVisible={addModalVisible}
          onSubmit={(value) => handleAdd(value)}
          onCancel={() => handleAddModalVisible(false)}
        />
      )}
      {editInfoVisible && tenant && (
        <EditForm
          tenant={tenant}
          onSubmit={editInfoEvent}
          onCancel={() => setEditInfoVisible(false)}
          visibleHandler={() => setEditInfoVisible(false)}
          modalVisible={editInfoVisible}
        />
      )}

      <Modal
        footer={null}
        open={passwordVisible}
        style={{ marginBottom: 100 }}
        centered
        title="修改密码"
        destroyOnClose
        onCancel={() => {
          setPasswordVisible(false);
        }}
      >
        <ProForm
          layout="horizontal"
          onFinish={async (value) => {
            const values = {
              password: value.password,
              id: tenant?.id || '0',
            };
            const hide = message.loading('正在修改');
            const res = await updateTenantPwd(values);
            hide();
            if (res.code === 0) {
              message.success(`修改成功`);
              setPasswordVisible(false);
              actionRef.current?.reload();
              return true;
            } else {
              message.error(`${res.message}`);
              return false;
            }
          }}
        >
          <Form.Item
            name="password"
            label="新密码"
            rules={[{ required: true, message: '新密码不能为空' }]}
          >
            <Input type="password" />
          </Form.Item>
        </ProForm>
      </Modal>
    </PageHeaderWrapper>
  );
};
